package com.lovely3x.paymentlibrary.wechatpay;

import com.lovely3x.common.BuildConfig;
import com.lovely3x.common.managements.pay.IPayCallBack;
import com.lovely3x.common.managements.pay.InitHook;
import com.lovely3x.common.managements.pay.PayAction;
import com.lovely3x.common.managements.pay.PayRequest;
import com.lovely3x.common.managements.pay.PaymentManager;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.security.MessageDigest;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * Created by lovely3x on 16/7/15.
 * <p>
 * 微信支付的工具类
 * 通过{@link WeChatPayAction#genPayReq}获取生成的订单号
 */
public class WeChatPayAction implements PayAction, InitHook<PaymentManager> {

    public static final WeChatPayAction INSTANCE = new WeChatPayAction();
    public static IWXAPI wxMsgApi;

    private WeChatPayAction() {
    }

    private static final String API_KEY = BuildConfig.WX_API_KEY; // api key 密钥
    private static final String APP_ID = BuildConfig.WX_APP_ID;//app id
    private static final String PID = BuildConfig.WX_PID;//商户id

//    wxMsgApi.sendReq(genPayReq(payRequest.getTn(), payRequest.getSign(),payRequest.getPrepayid(),payRequest.getNoncestr(),
// payRequest.getTimestamp()));

    private PayReq genPayReq(String orderId, String sign, String Prepayid, String Noncestr, String Timestamp) {

        PayReq req = new PayReq();

        req.appId = APP_ID;
        req.partnerId = PID;
        req.prepayId = Prepayid;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = Noncestr;
        req.timeStamp = Timestamp;

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));//appid
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));//: 生成签名的时候需要你自己设置随机字符串,noncestr就是你生成签名的时候那个随机字符串
        signParams.add(new BasicNameValuePair("package", req.packageValue));//微信签名信息
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));//商户号
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));//订单号
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));// 时间戳
        req.sign = genAppSign(signParams);
        return req;
    }

    private String genNonceStr() {
        Random random = new Random();
        return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }

        sb.append("key=");
        sb.append(API_KEY);

        return getMessageDigest(sb.toString().getBytes()).toUpperCase();
    }

    private static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean pay(PayRequest payRequest, IPayCallBack.PayMethod payMethod) {
        if (payMethod == IPayCallBack.PayMethod.WeChatPay) {
            wxMsgApi.sendReq(genPayReq(payRequest.getTn(), payRequest.getSign(), payRequest.getPrepayid(), payRequest.getNoncestr(), payRequest.getTimestamp()));
            return true;
        }
        return false;
    }

    @Override
    public void onInit(PaymentManager paymentManager) {
        paymentManager.registerPayAction(INSTANCE);

        wxMsgApi = WXAPIFactory.createWXAPI(paymentManager.getContext(), null);

        // 将该app注册到微信
        wxMsgApi.registerApp(APP_ID);
    }
}
